package cn.qn.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能说明：用来存储业务定义的sessionId和连接的对应关系
 *       利用业务逻辑中组装的sessionId获取有效连接后进行后续操作
 */
@Slf4j
public class WebSocketUtils {

    private static List<Session> sessions=new ArrayList<>();

    public static Map<String, List<Session>> clients = new ConcurrentHashMap<>();

    public static void put(String userId, Session session){
        List<Session> clientSession=new ArrayList<>();
        if(clients.containsKey(userId)){
            clientSession=clients.get(userId);
        }

        clientSession.add(session);
        clients.put(userId,clientSession);
    }

    public static List<Session> get(String userId){
        return clients.get(userId);
    }

    public static void remove(String userId,String sessionId){

        List<Session> clientSession=clients.get(userId);

        if(null==clientSession||clientSession.isEmpty()){
            clients.remove(userId);
        }else{
            for(Session session:clientSession){
                if(sessionId.equals(session.getId())){
                    clientSession.remove(session);
                    break;
                }
            }

        }

    }

    public static void removeAll(String userId){
        clients.remove(userId);
    }
    /**
     * 判断是否有连接
     * @param userId
     * @return
     */
    public static boolean hasConnection(String userId) {
        return clients.containsKey(userId);
    }

    /**
     * 發送消息
     * @param clientId
     * @param message
     * @return
     */
    public static boolean sendMessage(String clientId,String message) {
        if (clients.containsKey(clientId)) {
            List<Session> clientList=clients.get(clientId);
            try {
                for(Session session:clientList){
                    session.getBasicRemote().sendText(message);
                }
                return true;
            } catch (IOException e) {
                log.error("发送websocket错误",e);
                return false;
            }
        }else {
            return false;
        }

    }
}